import { getToken, setToken, removeToken,setTimeStamp } from '@/utils/auth'
import {loginApi,getInfoApi,getUserDetailById} from '@/api/user.js'
const state = {
  token: getToken(),
  //用户信息
  userInfo: {

  }
}
const mutations = {
  //保存token
  setToken(state, payload) {
    //保存到vuex
    state.token=payload
    //保存到cookie
    setToken(payload)
  },
  //清除token
  removeToken(state) {
    state.token = null
    removeToken()
  },
  //保存用户信息
  saveUserInfo(state, payload) {
    state.userInfo=payload
  },
  //清除用户信息
  removeUserInfo(state) {
    state.userInfo={}
  }
}
const actions = {
  //完成登出
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  },
  //完成登录
  async login(context, payload) {
    try {
      var res = await loginApi(payload)
      console.log(res);
      //响应拦截器简写res.data
      if (res.success) {
        const token = res.data
        context.commit('setToken', token)
        //设置时间戳
        setTimeStamp()
      }
    } catch(err) {
      // console.log(err.message);
      //返回错误信息给登录页,防止登录页错误仍然执行跳转
      return Promise.reject(err)
    }
  },
  //获取用户信息
  async getUserInfo(context) {
    const res = await getInfoApi()
    // console.log(res);
    const baseRes = await getUserDetailById(res.data.userId)
    const result={...res.data,...baseRes.data}
    context.commit('saveUserInfo', result)
    return result
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

